package com.dezheyun.service.impl;

import com.dezheyun.dao.DzUserMapper;
import com.dezheyun.domain.DzUser;
import com.dezheyun.service.DzUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class DzUserServiceImpl implements DzUserService {

    @Autowired
    private DzUserMapper dzUserMapper;

    @Override
    public List<DzUser> findAll() {
        return dzUserMapper.findAll();
    }

    @Override
    public DzUser selectOne(String username) {
        return dzUserMapper.selectOne(username);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        DzUser user = selectOne(username);
        if (Objects.isNull(user) && !username.equals(user.getUserName())) {
            throw new RuntimeException("该用户不存在！");
        }

        List<GrantedAuthority> authorities = new ArrayList<>();
        SimpleGrantedAuthority auth = new SimpleGrantedAuthority("ROLE_ROOT");
        authorities.add(auth);
        UserDetails userDetails = new User(user.getUserName(), user.getPassWord(),
                true, true, true, true, authorities);

        return userDetails;
    }
}
